<?php

namespace App\Http\Controllers;

use App\Events\OrderCompletedEvent;
use App\Extend\Payssion as PayssionLibrary;
use App\Models\OrderInfo;
use App\Services\OrderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class WebhookController extends Controller
{
    public function airwallex(Request $request)
    {
        try {
            $timestamp = $request->header('x-timestamp');
            $signature = $request->header('x-signature');
            $body = file_get_contents('php://input');

            Log::info("WebhookController::airwallex timestamp " . date('Y-m-d H:i:s') . "\n" . $timestamp);
            Log::info("WebhookController::airwallex signature " . date('Y-m-d H:i:s') . "\n" . $signature);
            Log::info("WebhookController::airwallex " . date('Y-m-d H:i:s') . "\n" . $body);

            $sign = hash_hmac('sha256', $timestamp . $body, env('AIRWALLEX_WEBHOOK_KEY'));
            if ($signature != $sign) {
                Log::info("WebhookController::airwallex 验签失败");
                return response('Signature verification failed', 400);
            }
            $data = json_decode($body, true);
            if ($data['name'] != 'payment_intent.succeeded') {
                return response('Payment failed or other state', 400);
            }
            if (!isset($data['data']['object']['merchant_order_id']) || empty($data['data']['object']['merchant_order_id'])) {
                return response('Invalid content', 400);
            }
            $transaction_id = $data['data']['object']['id'];
            $order_nu = $data['data']['object']['merchant_order_id'];
            $orderInfo = OrderInfo::where('order_nu', $order_nu)->where('transaction_id', $transaction_id)->first();
            if (empty($orderInfo)) {
                return response('Invalid transaction id', 400);
            }

            $result = (new OrderService())->paySuccess($orderInfo->order_nu);
            if ($result['code'] != 0) {
                return response('Recharge failure', 400);
            }

            // 订单完成事件
            event(new OrderCompletedEvent($orderInfo));

            return response('Payment success');
        } catch (\Exception $e) {
            return response('Recharge failure', 400);
        }
    }

    public function payssion(Request $request)
    {
        try {
            $params = $request->all();
            Log::info("WebhookController::payssion " . date('Y-m-d H:i:s') . "\n" . json_encode($params));
            if (empty($params)) {
                return response('Invalid content', 400);
            }
            if (empty($params['app_name']) || !in_array($params['app_name'], ['ipxproxy'])) {
                return response('Invalid application', 400);
            }
            $sign = (new PayssionLibrary())->getNotifySign($params['pm_id'], $params['amount'], $params['currency'], $params['order_id'], $params['state']);
            if ($sign != $params['notify_sig']) {
                return response('Signature verification failed', 400);
            }
            if ($params['state'] != 'completed') {
                return response('Payment failed or other state', 400);
            }

            $transaction_id = $params['transaction_id'];
            $orderInfo = OrderInfo::where('transaction_platform', 'Payssion')->where('transaction_id', $transaction_id)->first();
            if (empty($orderInfo)) {
                return response('Invalid transaction id', 400);
            }

            $result = (new OrderService())->paySuccess($orderInfo->order_nu);
            if ($result['code'] != 0) {
                return response('Recharge failure', 400);
            }

            // 订单完成事件
            event(new OrderCompletedEvent($orderInfo));

            return response('Payment success');
        } catch (\Exception $e) {
            return response('Recharge failure', 400);
        }
    }
}
